package com.example.library;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

public class ProportionRelativeLayout extends RelativeLayout
{
    public float mScale;
    
    private float mOffsetY;
    
    public ProportionRelativeLayout(Context context)
    {
        super(context);
    }
    
    public ProportionRelativeLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        
        init(attrs);
    }
    
    private void init(AttributeSet attrs)
    {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ProportionRelativeLayout);
        mScale = typedArray.getFloat(R.styleable.ProportionRelativeLayout_scale, -1);
        
        if (mScale == -1) {
            float scaleProvideX = typedArray.getFloat(R.styleable.ProportionRelativeLayout_scaleProvideX, -1);
            float scaleProvideY = typedArray.getFloat(R.styleable.ProportionRelativeLayout_scaleProvideY, -1);
            mOffsetY = typedArray.getDimensionPixelOffset(R.styleable.ProportionRelativeLayout_offsetY, 0);
            if (scaleProvideX > 0 && scaleProvideY > 0) {
                mScale = scaleProvideY / scaleProvideX;
            }
        }
        typedArray.recycle();
        
    }
    
    public ProportionRelativeLayout(Context context, AttributeSet attrs,
                                    int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }
    
    @SuppressLint("NewApi")
    public ProportionRelativeLayout(Context context, AttributeSet attrs,
                                    int defStyleAttr, int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
    
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        
        if (mScale > 0)
        {
            super.onMeasure(widthMeasureSpec,
                    MeasureSpec.makeMeasureSpec((int) (MeasureSpec.getSize(widthMeasureSpec)
                            * mScale + mOffsetY),
                            MeasureSpec.getMode(widthMeasureSpec)));
        }
        else
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
    
    public void setOffsetY(float offsetY)
    {
        mOffsetY = offsetY;
        invalidate();
        
    }
    
    public void setWidthAndHeightScale(float scale)
    {
        mScale = scale;
        invalidate();
    }
}
